<?php


namespace app\admin\controller\user;

use app\admin\model\SystemAdmin;
use app\admin\model\SystemAuth;
use app\user\model\User as Model;
use app\user\model\UserGrade;
use app\common\controller\AdminController;
use app\user\model\UserRichesLog;
use think\App;

/**
 * @ControllerAnnotation(title="用户管理")
 * Class User
 * @package app\admin\controller\system
 */
class User extends AdminController
{

    use \app\admin\traits\Curd;

    protected $sort = [
        'id'   => 'desc',
    ];
    protected $allowModifyFields = [
        'status',
        'sort',
        'no_audit',
        'is_admin',
        'title'
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new Model();

        $arr = (new UserGrade())->order('id asc')->select()->toArray();
        $this->group_list = array_column($arr, 'name', 'id');
        $this->assign('group_list', $this->group_list);

    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            try {
                $post['uuid']=md5(uniqid() . microtime());
                $save=$this->model->createNew($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }

        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        $uid=$post['id'];
        $row = $this->model->find($uid);
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);

            if($post['field']=='is_admin'){
                if($post['value']==1){
                    SystemAdmin::create([
                        'username'=>$row['username'],
                        'user_id'=>$uid,
                        'head_img'=>$row['avatar'],
                    ]);
                }else{
                    SystemAdmin::where('user_id',$uid)->delete();
                }
            }

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }


    /**
     * 批量创建用户
     */
    public function batchAddUser()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            //从官网获取随机用户名
            $res = Model::getRandNames($params['num']);
            if (!$res['data']) {
                return json(array('code' => 0, 'msg' => '未能用官方服务器获取到数据，请单个创建吧'));
            }
            $names = $res['data'];
            $realNum = count($names);
            $data = [];
            $new=0;
            for ($i = 0; $i < $realNum; $i++) {
                $name = trim($names[$i]);
                $_data['uuid'] =md5(uniqid() . microtime());
                $_data['salt'] = create_random_str(18);
                $_data['avatar'] = '/static/common/images/avatars/' . $i . '.jpg';
                $_data['username'] = 'u_' . create_random_str(6).rand(100,9999);
                $_data['nickname'] = $name;
                $_data['password'] = md5($params['password'] . $_data['salt']);
                Model::createNew($_data);
                $new++;
            }
            if ($new) {
                return success('成功创建' . $new . '个系统专用账号,密码均为' . $params['password']);
            } else {
                return fail('添加失败');
            }
        }

    }
    public function changePassword($id){
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $user=$this->model->find($id);
            $user->password=md5($params['value'] . $user['salt']);
            $res=$user->save();
            if($res) {
                return success('修改成功');
            }else{
                return fail('修改失败');
            }
        }
    }
    public function changeScore($id){

       if ($this->request->isPost()) {
                $params = $this->request->post();
                $addMoney=$params['value'];
                $res=UserRichesLog::note(abs($addMoney), $id, '管理员操作',$addMoney>0?1:0);
                if($res['code']==1) {
                    return success('修改成功');
                }else{
                    return json($res);
                }
       }

    }
}